<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/18
 * Time: 16:47
 */

namespace app\admin\controller;


use think\Exception;
use think\Validate;
use think\Session;
class LoginController extends CommonController
{

    protected $is_strictly      =   false;//此方法不需要对对字段做严格的验证
    protected $initModel        =   true;
    protected $controller       =   'User';
    public    $tmp_method       =   ['login'=>'POST'];

    /**
     * @return \think\response\Json
     */
    public function login(){
        try{
            $this->_beforeDecorate();
            $result                 =   $this->request->isPost();
            if($result===false){throw new Exception('抱歉请求的方法不允许',self::METHOD_NOT_ALLOW);}
            $param                  =   $this->request->post();
            $result                 =   $this->_checkLogin($param);
            if(true!==$result){throw new Exception('抱歉参数错误',self::BAD_REQUEST_CODE);}
            $result                 =   $this->model->check_login($param);
            if(false===$result){throw new Exception($this->model->getError(),self::SUCCESS_CODE);}
            $param                  =is_array($param)?array_merge($param,$result):$param;
            // 设置登录的UID设置为常量以便后面调用   这里不用担心会覆盖应为我们会话的session_id是唯一的
            if(false===Session::has('UID')){Session::set('UID',$param['id']);}
            //设置当前的uid
            $this->_endDecorate();
            return $this->_success($param,'登录成功');
        }catch (Exception $exception){
            $data= ['data'=>'','status'=>self::ERROR_CODE,'info'=>$exception->getMessage()];$code=$exception->getCode();
            return $this->_error($data,$code);
        }
    }


    /**
     * @param $data
     * @return bool
     */
    private function _checkLogin($data){
        $rule                   =[
            'name'      =>['require','min'=>11,'max'=>12],
            'password'  =>['require','min'=>6],
        ];
        $message=[
            'name.require'=>'请填写用户名称，或电话号码',
            'name.min'=>'抱歉名称需大于等11位数的电话号码',
            'name.max'=>'抱歉名称需小于等于12位数',
            'password.require'=>'抱歉请填写密码',
            'password.min'=>'密码至少是6位密码串',
        ];
        $validate       =   new Validate($rule,$message);
        $result         =   $validate->check($data);
        $result         =  $result?true:$validate->getError();
        return $result;
    }

}